import pandas as pd
import tushare as ts
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor

import QUANTAXIS as QA

# ts_token = '17056d23a59ab71cb979c6a30185e092aba605c4544dac900a3eb7f8'
# end = '2020-05-22'
# duration = QA.QA_util_get_pre_trade_date_list(end, n=5)
# pro = ts.pro_api('17056d23a59ab71cb979c6a30185e092aba605c4544dac900a3eb7f8')
# print(pro.query('moneyflow_hsgt', start_date='20200125', end_date='20200618'))
# hs300 = ts.get_hs300s()
# codes = hs300['code'].to_list()
# codes.remove('600816')  # ST
# codes = ['600496', '300044', '601633', '002415', '000100', '300118', '000333', '000002']
codes = ['000568']
data = QA.QA_fetch_stock_day_adv(codes, '2020-05-01', '2020-10-28')
# ind = data.add_func(QA.QA_indicator_THS_JDFJ)
# ind = data.add_func(QA.QA_indicator_THS_JMDD)
# ind = data.add_func(QA.QA_indicator_THS_ZLXC1)
# ind = data.add_func(QA.QA_indicator_THS_ZQMM)
ind = data.add_func(QA.QA_indicator_MACD_QTDS)

_data_show = data.data.copy()
# _data_show['buy'] = 0
# _date = None
# for items in data.panel_gen:
#     if _date != items.date[0]:
#         # print('try to settle')
#         _date = items.date[0]
#         # if _date._date_repr not in duration:
#         #     continue
#         # print(_date)
#
#     for item in items.security_gen:
#         if item.index.levels[0][0] not in ind.index.levels[0]:
#             continue
#         if ind.loc[item.index].B.iloc[0] > 0:
#             _data_show.loc[(_date, item.index.levels[1][0]), 'buy'] = 1
#             print('buy %s in %s' % (item.index.levels[1][0], _date))
#
#         elif ind.loc[item.index].S.iloc[0] < 0:
#             _data_show.loc[(_date, item.index.levels[1][0]), 'buy'] = -1
#             print('sell %s in %s' % (item.index.levels[1][0], _date))

# _data_show[['close', 'buy']].plot()
# ind.plot()
df_all = pd.concat([_data_show, ind], axis=1)
df_all = df_all.dropna().unstack()
figure = plt.figure()
axes1 = figure.add_subplot(411)
axes2 = figure.add_subplot(412)
axes3 = figure.add_subplot(413)
axes4 = figure.add_subplot(414)
axes1.plot(df_all.index, df_all['close'])
# axes2.plot(df_all.index, df_all[['V3', 'V4']])
# axes3.plot(df_all.index, df_all['V5'])
# axes4.plot(df_all.index, df_all[['B', 'S']])
axes2.plot(df_all.index, df_all['DIF'])
axes2.plot(df_all.index, df_all['DEA'])
axes2.plot(df_all.index, df_all['MACD'])
axes3.plot(df_all.index, df_all[['U_SHAPE', 'DEA_RED']])
axes4.plot(df_all.index, df_all[['B']])

left, right = axes2.get_xlim()
axes2.hlines(y=0, xmin=left, xmax=right, linestyles='dashed')
multi = MultiCursor(figure.canvas, (axes1, axes2, axes3, axes4), color='r', lw=1)
plt.show()
